<?php


use App\Http\Admin\Service\Base\DevAuxService;
use Sc\Util\HtmlElement\El;
use Sc\Util\HtmlStructure\Html\Html;

Html::create('a');
Html::css()->load('https://unpkg.com/layui@2.10.0/dist/css/layui.css');
Html::js()->load('https://unpkg.com/layui@2.10.0/dist/layui.js');

$devAuxService = DevAuxService::aop();
$tables  = $devAuxService->getAllTableInfo();

$tableEls = El::fictitious();
$menus = El::double('dl');
$index = 1;
$createSqls = [];

$tables = array_map(function ($item) use ($devAuxService, $tableEls, $menus, &$index, &$createSqls){
    $fields = $devAuxService->getFields($item->TABLE_NAME);
    $createSql = $devAuxService->getCreateSql($item->TABLE_NAME);
    $createSqls[$item->TABLE_NAME] = base64_encode($createSql);
    $menus->append(El::double('li')->append(
        El::double('div')->setStyle('{display: inline-block;min-width: 20px}')
            ->append($index)->append('、'),
        El::a($item->TABLE_COMMENT . "({$item->TABLE_NAME})")->setAttr("href", "#" . $item->TABLE_NAME)
    )->addClass('nav-item'));

    $table = El::double('table')->addClass('layui-table');
    $table->append(El::double('tr')->append(
        El::double('th')->text('字段名')->setAttr('width', 180),
        El::double('th')->text('字段类型')->setAttr('width', 180),
        El::double('th')->text('字段注释'),
    ));

    array_map(function ($item) use ($table){
        $table->append(El::double('tr')->append(
            El::double('td')->text($item->COLUMN_NAME),
            El::double('td')->text($item->COLUMN_TYPE),
            El::double('td')->text($item->COLUMN_COMMENT ?: $item->COLUMN_NAME),
        ));
    }, $fields);

    $currentEl = El::div()->setId($item->TABLE_NAME)->addClass('anchor-section');

    $currentEl->append(El::double('h2')->append(
        El::span($index)
            ->append('、')
            ->append($item->TABLE_COMMENT)
            ->append("({$item->TABLE_NAME})"),
        El::a("查看SQL")
            ->setStyle("{cursor: pointer;color: #00a2d4;font-size: 15px}")
            ->setAttr('onclick', "showSql('{$item->TABLE_NAME}')"),
        El::a("提取信息")
            ->setStyle("{cursor: pointer;color: #00a2d4;font-size: 15px}")
            ->setAttr('onclick', "showSql('{$item->TABLE_NAME}', 1)")
    ));
    $index++;
    $currentEl->append($table);
    $tableEls->append($currentEl);
}, $tables);

Html::js()->defVar('createSqls', $createSqls);
$defJsFnBase64Decode = \Sc\Util\HtmlStructure\Html\Common::defJsFnBase64Decode();
Html::js()->defFunc('showSql', ['key', 'istq'], <<<JS
    if (istq){
        return layer.open({
            type:1,
            offset: 'r',
            shade:0,
            title:layui.jquery('#' + key).find('h2').find('span').text(),
            area:'900px',
            moveOut:true,
            tipsMore:true,
            content: layui.jquery('#' + key).find('table').prop('outerHTML')
        });
    }
    layer.open({
        shade:0,
        tipsMore:true,
        moveOut:true,
        content: highlightSQL($defJsFnBase64Decode(createSqls[key]))
    })
JS);

Html::css()->addCss(<<<CSS
/* SQL建表语句高亮样式 */
.sql-table-def {
  background: #f9f9f9;
  border-radius: 6px;
  border: 1px solid #e1e4e8;
  padding: 1rem;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.8;
  white-space: pre-wrap;
  overflow-x: auto;
  color: #333;
  margin: 1rem 0;
}

/* 建表关键字 */
.sql-kw {
  color: #007acc;
  font-weight: 600;
}

/* 数据类型 */
.sql-type {
  color: #9b7536;
}

/* 表名 */
.sql-table {
  color: #22863a;
}

/* 列名 */
.sql-col {
  color: #032f62;
}

/* 注释 */
.sql-cmt {
  color: #6a737d;
  font-style: italic;
}

/* 引号字符串 */
.sql-str {
  color: #d73a49;
}

/* 括号和逗号 */
.sql-punc {
  color: #24292e;
}

/* 约束定义 */
.sql-constraint {
  color: #6f42c1;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .sql-table-def {
    font-size: 13px;
    padding: 0.8rem;
  }
}

.nav-item.active,.nav-item>a.active {
  color: #007bff; /* 蓝色 */
  font-weight: 700;
}
CSS);


Html::js()->defCodeBlock(<<<'JS'
function highlightSQL(sql) {
  // 1. 先对整个SQL进行HTML转义，防止特殊字符问题
  let escapedSQL = escapeHTML(sql);
  
  // 2. 定义正则表达式模式（顺序很重要）
  const patterns = [
    // 注释
    // { regex: /(--.*?$|\/\*[\s\S]*?\*\/)/gm, type: 'sql-cmt' },
    // 字符串
    { regex: /('(?:\\'|[^'])*'|"(?:\\"|[^"])*")/g, type: 'sql-str' },
    // 数字
    { regex: /\b(\d+(?:\.\d+)?)\b/g, type: 'sql-num' },
    // 关键字
    { regex: /\b(CREATE|TABLE|PRIMARY|KEY|NOT|NULL|AUTO_INCREMENT|UNIQUE|DEFAULT|ENGINE|COMMENT|CHARSET|INT|BIGINT|DATETIME|VARCHAR|TEXT|PRIMARY\s+KEY|FOREIGN\s+KEY|REFERENCES|ON\s+DELETE|ON\s+UPDATE)\b/gi, type: 'sql-kw' },
    // 数据类型
    { regex: /\b(INT|BIGINT|DATETIME|VARCHAR|TEXT|TIMESTAMP|DECIMAL|TINYINT)\b/gi, type: 'sql-type' },
    // 约束
    { regex: /\b(NOT\s+NULL|AUTO_INCREMENT|DEFAULT|PRIMARY\s+KEY|UNIQUE|COMMENT)\b/gi, type: 'sql-constraint' },
    // 表名
    { regex: /CREATE\s+TABLE\s+(`[^`]+`|[^\s(]+)/gi, type: 'sql-table' },
    // 列名
    { regex: /^\s*(`[^`]+`|[^\s(]+)\s+(?=(INT|BIGINT|DATETIME|VARCHAR|TEXT|TIMESTAMP|DECIMAL|TINYINT))/gm, type: 'sql-col' },
    // 括号和逗号
    { regex: /([(),;])/g, type: 'sql-punc' }
  ];
  
  // 3. 按顺序应用正则表达式替换
  let highlighted = escapedSQL;
  patterns.forEach(pattern => {
    highlighted = highlighted.replace(pattern.regex, (match) => {
      return `<span class="${pattern.type}">${match}</span>`;
    });
  });
  
  return `<pre class="sql-table-def">${highlighted}</pre>`;
}

// 修复的HTML转义函数
function escapeHTML(str) {
  if (!str) return '';
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    // .replace(/'/g, '&#039;')
    ;
}

document.addEventListener("DOMContentLoaded", function() {
  // 获取所有导航项和锚点
  const navItems = document.querySelectorAll('.nav-item');
  const anchorSections = document.querySelectorAll('.anchor-section');

  // 缓存锚点位置（含偏移量，避免导航栏遮挡）
  const anchorPositions = [];
  const NAV_OFFSET = 0; // 导航栏高度（需与CSS中的margin-top保持一致）

  anchorSections.forEach((section, index) => {
    const position = section.offsetTop - NAV_OFFSET;
    anchorPositions[index] = position;
  });
    console.log(anchorPositions)
  // 滚动事件处理（带节流优化）
  let isThrottling = false;
  window.addEventListener('scroll', function() {
    if (isThrottling) return;
    isThrottling = true;
    requestAnimationFrame(() => {
      const scrollY = window.scrollY || document.documentElement.scrollTop;
      
      const activeIndex = anchorPositions.findIndex(pos => scrollY <= pos);
      
      // 更新导航项颜色
      navItems.forEach((item, index) => {
        item.classList.toggle('active', index === activeIndex);
      });
      console.log(123, activeIndex)
      isThrottling = false;
    });
  });
});
JS
);



return El::div()->setStyle("{width: 900px;margin: auto}")->append(
    El::double('h1')->setStyle('{text-align: center}')->text(\App\Util\Helper::getConfig('app_title', '') . '数据库表结构'),
    El::double('h3')->text('目录：'),
    $menus->setStyle('{position: fixed; top:50px;left: 50%;margin-left: -800px;height: calc(100% - 200px);overflow-y: auto}'),
    $tableEls
);

